/**
 * Copyright (c) 2014-now, secondriver (secondriver@yeah.net).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package secondriver.jfinal.rack.pugin.jcs;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.jcs.JCS;
import org.apache.jcs.access.CacheAccess;
import org.apache.jcs.access.GroupCacheAccess;
import org.apache.jcs.access.exception.CacheException;

import com.jfinal.plugin.IPlugin;

public class JCSPlugin implements IPlugin {

	private static final String DEFALUT_REGION = "defalut";

	private static final String DEFAULT_CACHE_CCF = "secondriver/jfinal/rack/pugin/jcs/cache.ccf";

	private String cacheCcf = DEFAULT_CACHE_CCF;

	public JCSPlugin() {

	}

	public JCSPlugin(String cacheCcf) {
		this.cacheCcf = cacheCcf;
	}

	@Override
	public boolean start() {
		if (null == cacheCcf || "".equals(cacheCcf)) {
			throw new RuntimeException("Please check cache configure file.");
		} else {
			this.getClass().getClassLoader();
			JCSPlugin.class.getClassLoader();
			URL url = Thread.currentThread().getContextClassLoader()
					.getResource("");
			File file = new File(url.getFile(), cacheCcf);
			if (!file.exists()) {
				throw new RuntimeException("Please check cache configure file.");
			} else {
				JCS.setConfigFilename(file.getAbsolutePath());
				return true;
			}
		}
	}

	public CacheAccess getCacheAccess(String region) throws CacheException {
		return JCS.getAccess(region);
	}

	public GroupCacheAccess getGroupCacheAccess(String region)
			throws CacheException {
		return JCS.getGroupAccess(region);
	}

	public CacheAccess getCacheAccess() throws CacheException {
		return JCS.getAccess(DEFALUT_REGION);
	}

	public GroupCacheAccess getGroupCacheAccess() throws CacheException {
		return JCS.getGroupAccess(DEFALUT_REGION);
	}

	@Override
	public boolean stop() {
		return false;
	}

	public static void main(String[] args) throws URISyntaxException {
		JCSPlugin plugin = new JCSPlugin();
		boolean rs = plugin.start();
		System.out.println(rs);
	}
}
